#include "VmdReverseTask.h"

EdsReverseTask::EdsReverseTask(void)
{
	Generator.Allocate(10);
	Receiver.Allocate(10);
	double side = 500;

	Generator.Push(-side/2, -side/2);
	Generator.Push(side/2, -side/2);
	Generator.Push(side/2, side/2);
	Generator.Push(-side/2, side/2);

	double x = -9.10428;
	double y = -2.89174 ;
	side = 1;

	Receiver.Push(x-side/2, y-side/2);
	Receiver.Push(x+side/2, y-side/2);
	Receiver.Push(x+side/2, y+side/2);
	Receiver.Push(x-side/2, y+side/2);

	Z = 0;
	Multiplier = 40*17920;
}



EdsReverseTask::~EdsReverseTask(void)
{
}

void EdsReverseTask::CalcAbnormalCurve( int iIndex, ConductiveLayer *iNewMedium, int iLayersCount )
{
	//check if need update cached curve
	bool recalc_cache = false;
	if(CacheLNum == 0 || CacheLNum != iLayersCount)
		recalc_cache = true;
	else
	{
		for(int i=0; i<CacheLNum; i++)
		{
			if(CachedL[i].Sigma != OldMedium[i].Sigma || CachedL[i].H != OldMedium[i].H)
			{
				recalc_cache = true;
				CachedL[i] = OldMedium[i];
			}
		}
	}
	if(recalc_cache)
	{
		Task.Init(OldMedium, LayersNum, &Generator, &Receiver);
		Task.Eds(Z, Times.Data, Times.GetSize(), CachedCurve.Data);
		for(int i=0; i<Times.GetSize(); i++)
			CachedCurve[i] *= Multiplier;
	}


	//calculate abnormal curve
	Task.Init(iNewMedium, iLayersCount, &Generator, &Receiver);
	Task.Eds(Z, Times.Data, Times.GetSize(), BufVector.Data);


	//fill actual curve
	for(int i=0; i<BufVector.GetSize(); i++)
	{
		BufVector[i] *= Multiplier;
		AbnomalCurves[iIndex][i].Y = (BufVector[i] - CachedCurve[i]);
		ActualCurves[iIndex][i].Y = BufVector[i];
	}
}

void EdsReverseTask::CalcActualCurve( int iIndex )
{	printf("act\n");
	Task.Init(Medium, LayersNum, &Generator, &Receiver);
	Task.Eds(Z, Times.Data, Times.GetSize(), BufVector.Data);


	//copy medium	
	CacheLNum = LayersNum;
	for(int i=0; i<CacheLNum; i++)
	{
		CachedL[i] = OldMedium[i];
	}


	//fill actual curve
	for(int i=0; i<BufVector.GetSize(); i++)
	{
		BufVector[i] *= Multiplier;
		ActualCurves[iIndex][i].Y = BufVector[i];	
		CachedCurve[i] = ActualCurves[iIndex][i].Y;
	}

	ActualCurves[iIndex].Filter();
}


void EdsReverseTask::AfterInit()
{
	Times.Allocate(OriginalCurves[0].GetSize());
	BufVector.Allocate(OriginalCurves[0].GetSize());
	CachedCurve.Allocate(OriginalCurves[0].GetSize());

	//fill times
	for(int i=0; i<OriginalCurves[0].GetSize(); i++)
	{
		Times[i] = OriginalCurves[0][i].X;
	}
}